/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web;

import ejb.UserBeanLocal;
import entities.User;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Jesus
 */
@ManagedBean
@RequestScoped
public class RegisterBean {

    @EJB
    private UserBeanLocal userBean;
    private User user;

    public RegisterBean() {
        user = new User();
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String register() {
        System.out.println("Registrando a " + user.getEmail());
        if (!user.getEmail().equals("") && !user.getFirstname().equals("") && !user.getLastname().equals("") && !user.getPassword().equals("")) {
            User userToInsert = userBean.findByEmail(user.getEmail().toLowerCase());
            // Si no existía previamente
            if (userToInsert != null) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                        FacesMessage.SEVERITY_ERROR, "El email introducido ya se encuentra registrado", ""));
            } else {
                User insertedUser = userBean.insert(user);
                if (insertedUser != null) {
                    FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", insertedUser);
                    return "main";
                }
            }
        } else {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(
                    FacesMessage.SEVERITY_ERROR, "Todos los campos son obligatorios", ""));
        }
        return "ERROR";
    }
}
